import sys
import base64
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from dao.classorm import classOrm
from dao.index import LoginSchema
from utils.json import JSONHandler
from components.messageBox import CustomMessageBox

class AuthWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.json = JSONHandler("./config/cache.json")
        self.setWindowTitle("用户认证")
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        # 设置窗口标志
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)

        # 隐藏标题栏
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowTitleHint)
        self.setFixedSize(500, 650)  # 增加窗口尺寸以适应全拼输入项

        # 使用堆叠布局管理两个界面
        self.stack = QStackedWidget()
        self.init_unauthenticated_ui()
        self.init_auth_form_ui()

        main_layout = QVBoxLayout(self)
        main_layout.addWidget(self.stack)
        self.setStyleSheet(self.get_stylesheet())

    def paintEvent(self, event):
        """绘制背景渐变色"""
        painter = QPainter(self)
        gradient = QLinearGradient(0, 0, self.width(), self.height())
        gradient.setColorAt(0, QColor(135, 206, 250))  # 浅蓝色
        gradient.setColorAt(1, QColor(221, 160, 221))  # 浅紫色
        painter.fillRect(self.rect(), gradient)

    def get_stylesheet(self):
        return """
        QWidget {
            font-family: '微软雅黑';
            color: #2c3e50;
        }

        /* 自定义标题栏 */
        #title_label {
            font-size: 24px;
            color: #2c3e50;
            padding: 20px;
        }

        /* 主按钮样式 */
        .primary-btn {
            background: #00A3FF;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-size: 16px;
            min-width: 150px;
        }
        .primary-btn:hover { background: #0088cc; }

        /* 提交按钮样式 */
        .submit-btn {
            background: #27ae60;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-size: 16px;
            min-width: 150px;
        }
        .submit-btn:hover { background: #219a52; }

        /* 自定义下拉框 */
        QComboBox {
            padding: 8px;
            border: 2px solid #bdc3c7;
            border-radius: 5px;
            selection-background-color: #3498db;
        }
        QComboBox::drop-down {
            width: 30px;
            border-left: 2px solid #bdc3c7;
        }
        QComboBox::down-arrow {
            image: url(arrow-down.png);
            width: 12px;
            height: 12px;
        }

        /* 上传按钮样式 */
        .upload-btn {
            border: 2px dashed #bdc3c7;
            border-radius: 10px;
            padding: 20px;
            background: rgba(255,255,255,0.8);
            margin-top: 15px;
        }
        .upload-btn:hover { border-color: #3498db; }
        """

    def get_classinfo(self):
        class_orm = classOrm().get_class()
        print(class_orm)
        return [i['class_name'] for i in class_orm]

    def init_unauthenticated_ui(self):
        page = QWidget()
        layout = QVBoxLayout(page)

        # 标题
        title = QLabel("你还未认证\n点击我去认证", alignment=Qt.AlignCenter)
        title.setObjectName("title_label")

        # 认证按钮
        btn = QPushButton("立即认证")
        btn.setCursor(Qt.PointingHandCursor)
        btn.setObjectName("primary-btn")
        btn.clicked.connect(lambda: self.stack.setCurrentIndex(1))

        layout.addStretch()
        layout.addWidget(title)
        layout.addWidget(btn, alignment=Qt.AlignCenter)
        layout.addStretch()

        self.stack.addWidget(page)

    def init_auth_form_ui(self):
        page = QWidget()
        layout = QVBoxLayout(page)
        layout.setContentsMargins(40, 30, 40, 30)
        layout.setSpacing(15)

        # 表单标题
        title = QLabel("用户认证", alignment=Qt.AlignCenter)
        title.setStyleSheet("font-size: 22px; color: #2c3e50;")

        # 图片预览容器
        preview_container = QWidget()
        preview_layout = QVBoxLayout(preview_container)
        preview_layout.setContentsMargins(0, 0, 0, 0)

        # 图片预览
        self.image_preview = QLabel()
        self.image_preview.setAlignment(Qt.AlignCenter)
        self.image_preview.setFixedSize(167, 200)  # 增大预览区域
        self.image_preview.setStyleSheet("""
            background: #f8f9fa;
            border: 2px dashed #bdc3c7;
            border-radius: 15px;
            margin-bottom: 10px;
        """)

        # 上传按钮
        self.upload_btn = QPushButton("点击上传真实照片")
        self.upload_btn.setObjectName("upload-btn")
        self.upload_btn.clicked.connect(self.upload_photo)

        preview_layout.addWidget(self.image_preview)
        preview_layout.addWidget(self.upload_btn, alignment=Qt.AlignCenter)

        # 班级选择
        class_label = QLabel("选择班级:")
        class_label.setStyleSheet("color: #7f8c8d; margin-top: 20px;")
        self.class_combo = QComboBox()
        self.class_combo.addItems(self.get_classinfo())

        # 姓名输入
        name_label = QLabel("姓名:")
        name_label.setStyleSheet("color: #7f8c8d;")
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("请输入姓名")
        self.name_input.setStyleSheet("""
            background: rgba(255,255,255,0.8);
            padding: 10px;
            border-radius: 8px;
            border: 2px solid #bdc3c7;
        """)

        # 全拼输入
        pinyin_label = QLabel("全拼:")
        pinyin_label.setStyleSheet("color: #7f8c8d;")
        self.pinyin_input = QLineEdit()
        self.pinyin_input.setPlaceholderText("请输入姓名全拼（如：zhangsan）")
        self.pinyin_input.setStyleSheet("""
            background: rgba(255,255,255,0.8);
            padding: 10px;
            border-radius: 8px;
            border: 2px solid #bdc3c7;
        """)

        # 提交按钮
        submit_btn = QPushButton("提交认证")
        submit_btn.setObjectName("submit-btn")
        submit_btn.setCursor(Qt.PointingHandCursor)
        submit_btn.clicked.connect(self.on_submit_clicked)

        # 布局组装
        layout.addWidget(title)
        layout.addWidget(preview_container, alignment=Qt.AlignCenter)
        layout.addWidget(class_label)
        layout.addWidget(self.class_combo)
        layout.addWidget(name_label)
        layout.addWidget(self.name_input)
        layout.addWidget(pinyin_label)  # 新增全拼标签
        layout.addWidget(self.pinyin_input)  # 新增全拼输入框
        layout.addStretch()
        layout.addWidget(submit_btn, alignment=Qt.AlignCenter)

        self.stack.addWidget(page)

    def upload_photo(self):
        path, _ = QFileDialog.getOpenFileName(
            self, "选择照片", "", "Images (*.png *.jpg *.jpeg)")
        if path:
            with open(path, 'rb') as f:
                photo_data = f.read()
            # 保存base64编码
            self.image_base64 = base64.b64encode(photo_data).decode('utf-8')
            self.upload_btn.setText("照片已上传")

            # 显示图片预览
            pixmap = QPixmap(path)
            self.image_preview.setPixmap(pixmap.scaled(
                self.image_preview.size(),
                Qt.KeepAspectRatio,
                Qt.SmoothTransformation
            ))

    def on_submit_clicked(self):
        """处理提交认证事件"""
        selected_class = self.class_combo.currentText()
        name = self.name_input.text().strip()
        pinyin = self.pinyin_input.text().strip()  # 获取全拼输入

        # 基础验证（可选）
        if not pinyin:
            CustomMessageBox().show_warning("请输入姓名全拼")
            return

        # 获取图片base64数据
        image_base64 = getattr(self, 'image_base64', '未上传图片')
        
        # 提交数据（包含全拼）
        LoginSchema().update_student(
            user_id=self.json.read()['user_id'],
            student={
                'class_name': selected_class,
                'name': name,
                'en_name': pinyin,  # 新增字段
                'auth_img': image_base64
            }
        )
        
        self.close()
        CustomMessageBox().show_success("认证成功，信息已提交，请重新登录")

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.drag_pos = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        if hasattr(self, 'drag_pos'):
            self.move(event.globalPos() - self.drag_pos)
            event.accept()